/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bomgrab;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;

import data.BOMData;
import data.BOMHeader;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import sunriseset.SunRiseSet;
import worker.BOMDataWorker;

/**
 *
 * @author bsmith
 */
public class BOMGrab {

    static final boolean formatted_yes = true;
    static final boolean formatted_no = false;

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String url) {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } catch (MalformedURLException ex) {
            java.util.logging.Logger.getLogger(BOMGrab.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(BOMGrab.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            java.util.logging.Logger.getLogger(BOMGrab.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(BOMGrab.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }

    public static void main(String[] args) throws IOException, JSONException, ParseException, Exception {
        observations();
        srs();
    }

    public static void observations() throws IOException, JSONException, ParseException, Exception {
        // Canberra for today and previous 2 days
        JSONObject json = readJsonFromUrl("http://www.bom.gov.au/fwo/IDN60903/IDN60903.94926.json");//https://graph.facebook.com/19292868552");
//        System.out.println(json.toString());
//        System.out.println(json);//.get("observations"));

        BOMHeader bomHeader = BOMDataWorker.getInstance().getHeaderFromJSONObjects(json);
        List<BOMData> bomDataPoints = BOMDataWorker.getInstance().getDataFromJSONObjects(bomHeader, json);

//        System.out.println("Header:\n" + bomHeader + "\n");
//        System.out.println("Record 1:" + "\n" + bomDataPoints.get(0));

        Calendar yesterdayC = Calendar.getInstance();
        yesterdayC.add(Calendar.DAY_OF_MONTH, -1);
        Date yesterday = yesterdayC.getTime();
        Calendar dayBeforeYesterdayC = Calendar.getInstance();
        dayBeforeYesterdayC.add(Calendar.DAY_OF_MONTH, -1);
        Date dayBeforeYesterday = dayBeforeYesterdayC.getTime();

        Map<Date, BOMData> bomDataMap = BOMDataWorker.getInstance().listToDateMap(bomDataPoints);
        List<BOMData> bomDataListForToday = BOMDataWorker.getInstance().getSortedBomDataListOnGivenDay(bomDataMap, new Date()); // today
        List<BOMData> bomDataListForYesterday = BOMDataWorker.getInstance().getSortedBomDataListOnGivenDay(bomDataMap, yesterday);
        List<BOMData> bomDataListForDayBeforeYesterday = BOMDataWorker.getInstance().getSortedBomDataListOnGivenDay(bomDataMap, dayBeforeYesterday);
//        System.out.println("BOM DATA for date (today) sorted by time ->");
//        for (BOMData bd : bomDataListForToday) {
//            System.out.println("  " + bd.getLocal_date_time());
//        }
        printStats("Yesterday", bomDataListForDayBeforeYesterday, bomDataListForYesterday);
        printStats("Today", bomDataListForYesterday, bomDataListForToday);
    }

    private static void printStats(String statsForWhatDay, List<BOMData> dayBefore, List<BOMData> day) {

        int minTempIndex = BOMDataWorker.getInstance().getMinimumTempIndex(day);
        int maxTempIndex = BOMDataWorker.getInstance().getMaximumTempIndex(day);
        int currentTempIndex = BOMDataWorker.getInstance().getLatestTempIndex(day);
        Float rainFallBefore9 = BOMDataWorker.getInstance().getRainFallBefore9(day, dayBefore);
        Float rainFallAfter9 = BOMDataWorker.getInstance().getRainFallAfter9(day, new Date());
        String observations = BOMDataWorker.getInstance().getObservationString(day);

//        System.out.println(String.format("MIN:%02.2f at %s", bomDataListForToday.get(minTempIndex).getAir_temp(), BOMDataWorker.getInstance().getTimeString(bomDataListForToday.get(minTempIndex).getLocal_date_time())));
//        System.out.println(String.format("MAX:%02.2f at %s", bomDataListForToday.get(maxTempIndex).getAir_temp(), BOMDataWorker.getInstance().getTimeString(bomDataListForToday.get(maxTempIndex).getLocal_date_time())));
//        System.out.println(String.format("CURRENT:%02.2f at %s", bomDataListForToday.get(currentTempIndex).getAir_temp(), BOMDataWorker.getInstance().getTimeString(bomDataListForToday.get(currentTempIndex).getLocal_date_time())));
//        System.out.println(String.format("Rain before 9:%02.2f", rainFallBefore9));
//        System.out.println(String.format("Rain after 9:%02.2f", rainFallAfter9));
//        System.out.println(String.format("Observations: %s", observations));
        if (day == null || day.size() == 0) {
            java.util.logging.Logger.getLogger(BOMGrab.class.getName()).log(Level.WARNING, "day list is null or empty");
            return;
        }
        System.out.println("Day: " + statsForWhatDay);
        System.out.format("||Min| %02.2f degrees at %s\n", day.get(minTempIndex).getAir_temp(), BOMDataWorker.getInstance().getTimeString(day.get(minTempIndex).getLocal_date_time()));
        System.out.format("||Max| %02.2f degrees at %s\n", day.get(maxTempIndex).getAir_temp(), BOMDataWorker.getInstance().getTimeString(day.get(maxTempIndex).getLocal_date_time()));
        System.out.format("||Currently| %02.2f degrees at %s\n", day.get(currentTempIndex).getAir_temp(), BOMDataWorker.getInstance().getTimeString(day.get(currentTempIndex).getLocal_date_time()));
        System.out.format("||Rainfall (up to 9am, up to %s) | %02.2f, %02.2f mm\n", BOMDataWorker.getInstance().getTimeString(Calendar.getInstance().getTime()), rainFallBefore9, rainFallAfter9);
        System.out.format("||Observations| %s\n", observations);
    }

    public static void srs() {
//        Calendar today = Calendar.getInstance();
//        SunRiseSet srs = new SunRiseSet(SRSCity.Canberra, today.get(Calendar.YEAR), today.get(Calendar.MONTH) + 1, today.get(Calendar.DAY_OF_MONTH));
//        srs.printSunrise(formatted_yes);
//        srs.printSunset(formatted_yes);
//        srs.printDaylight(formatted_yes);
        SunRiseSet srs = new SunRiseSet();
        srs.doCanberra();
    }
}
